﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace XinYiOffice.Common
{
    public class CookieHelper
    {
        public CookieHelper() { }

        public static string GetCookie(string CookieName)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[CookieName];
            
            if (cookie != null)
                return cookie.Value;
            else
                return null;
        }
        public static string GetCookie(string ParentName, string CookieName)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[ParentName];
            if (cookie != null)
                return HttpContext.Current.Request.Cookies[ParentName][CookieName];
            else
                return null;
        }

        public static void Set(string CookieName, string CookieValue, int ExpiresDay)
        {
            HttpCookie cookie = new HttpCookie(CookieName);
            cookie.Value = CookieValue;
            if (ExpiresDay > 0)
                cookie.Expires = DateTime.Now.AddDays(ExpiresDay);
            HttpContext.Current.Response.AppendCookie(cookie);
        }

        public static void Set(string ParentName, string CookieName, string CookieValue, int ExpiresDay)
        {
            HttpCookie cookie;
            if (GetCookie(ParentName) == null)
                cookie = new HttpCookie(CookieName);
            else
                cookie = HttpContext.Current.Request.Cookies[ParentName];
            cookie.Values[CookieName] = CookieValue;
            if (ExpiresDay > 0)
                cookie.Expires = DateTime.Now.AddDays(ExpiresDay);
            HttpContext.Current.Response.AppendCookie(cookie);
        }

        public static void Remove(string CookieName)
        {
            if (System.Web.HttpContext.Current.Request.Cookies[CookieName]!=null)
            {
                HttpCookie hc = new HttpCookie(CookieName);

                hc.Expires = DateTime.Today.AddDays(-10);
                hc.Value = null;

                HttpContext.Current.Response.Cookies.Add(hc);
            }
        }

        public static void Remove(string ParentName, string CookieName)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[ParentName];
            cookie.Values.Remove(CookieName);
        }
    }
}
